from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.conf import settings

import hashlib

from .models import Texture
from .forms import UploadForm

def index(request):
    return render(request, 'main/index.html')

def upload(request):
    if request.method != 'POST':
        return render(request, 'main/upload.html')
    else:
        picture = request.FILES.get('picture')
        file = b''
        for chunk in picture.chunks():
            file += chunk
        hash = hashlib.sha256(file).hexdigest()
        model = Texture()
        model.name = request.POST.get('name')
        model.hash = hash
        model.save()

        url = settings.MEDIA_ROOT + '/' + hash
        with open(url, 'wb') as f:
            f.write(file)
        return HttpResponseRedirect(reverse('main:skinlib'))

def skinlib(request):
    textures = Texture.objects.all()
    return render(request, 'main/skinlib.html', {'textures': textures})
